package com.huilian.iotbox.admin.wap.service.impl;

import com.huilian.iotbox.admin.wap.dao.MemberDao;
import com.huilian.iotbox.admin.wap.dao.StatsStoreDao;
import com.huilian.iotbox.admin.wap.dao.StatsUserDao;
import com.huilian.iotbox.admin.wap.service.MemberStoreBalanceService;
import com.huilian.iotbox.admin.wap.service.StatsCustomerService;
import com.huilian.iotbox.data.dto.StatsStoreDto;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.vo.StatsStoreVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author LinYinDong
 * @date 2023/8/3 16:42
 */
@Service
public class StatsCustomerServiceImpl implements StatsCustomerService {
    @Resource
    private MemberDao memberDao;
    @Autowired
    private MemberStoreBalanceService memberStoreBalanceService;
    @Resource
    private StatsUserDao statsUserDao;
    @Resource
    private StatsStoreDao statsStoreDao;

    @Override
    public StatsStoreVo findStoreCustomer(StatsStoreDto statsStoreDto) {
        StatsStoreVo statsStoreVo = null;
        StatsStoreVo todayStoreVo;
        StatsStoreVo thisMonthStatsStoreVo;
        //当天
        if (statsStoreDto.getDayType() == 0) {
            statsStoreVo = this.findTodayStatsStoreFromOrder(statsStoreDto);
        } else if (statsStoreDto.getDayType() == -1) {
            statsStoreDto.setType(1);
            statsStoreVo = this.findFromStatsStore(statsStoreDto);
            if (statsStoreDto.getEndDateStr().equals(DateTimeUtils.getCurrentDateStr())) {
                todayStoreVo = this.findTodayStatsStoreFromOrder(statsStoreDto);
                this.twoStatsStoreVoAdd(todayStoreVo, todayStoreVo);
            }
        }else{
            switch (statsStoreDto.getDayType()) {
                case 1:
                    //凌晨0点到六点调用实时统计的方法
                    Date date = new Date();
                    String pattern = "HH";
                    Locale locale = Locale.getDefault();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, locale);
                    String time = simpleDateFormat.format(date);
                    Integer hour = Integer.parseInt(time);
                    if(hour >= 0 && hour <= 5){
                        statsStoreDto.setHour(hour);
                        statsStoreVo = this.findTodayStatsStoreFromOrder(statsStoreDto);
                    }else{
                        //昨天
                        statsStoreDto.setStartDateStr(DateTimeUtils.getYesterday());
                        statsStoreDto.setEndDateStr(DateTimeUtils.getYesterday());
                        statsStoreDto.setType(1);
                        statsStoreVo = this.findFromStatsStore(statsStoreDto);
                    }
                    break;
                case 2:
                    //本周
                    statsStoreDto.setStartDateStr(DateTimeUtils.getWeekFirstDay());
                    statsStoreDto.setEndDateStr(DateTimeUtils.getCurrTime());
                    statsStoreDto.setType(1);
                    statsStoreVo = this.findFromStatsStore(statsStoreDto);
                    //当天
                    todayStoreVo = this.findTodayStatsStoreFromOrder(statsStoreDto);
                    this.twoStatsStoreVoAdd(todayStoreVo, todayStoreVo);
                    break;
                case 3:
                    //本月
                    statsStoreVo = this.getThisMonth(statsStoreDto);
                    break;
                case 4:
                    //今年
                    statsStoreDto.setStartDateStr(DateTimeUtils.getYearFirstDayTimeYM());
                    statsStoreDto.setEndDateStr(DateTimeUtils.getMonthYM());
                    statsStoreDto.setType(2);
                    statsStoreVo = this.findFromStatsStore(statsStoreDto);
                    //本月
                    thisMonthStatsStoreVo = this.getThisMonth(statsStoreDto);
                    this.twoStatsStoreVoAdd(statsStoreVo, thisMonthStatsStoreVo);
                    break;
                case 5:
                    //上月
                    statsStoreDto.setStartDateStr(DateTimeUtils.getPreviousMonthYM());
                    statsStoreDto.setEndDateStr(DateTimeUtils.getPreviousMonthYM());
                    statsStoreDto.setType(2);
                    statsStoreVo = this.findFromStatsStore(statsStoreDto);
                    break;
            }
        }
        return statsStoreVo;
    }

    private StatsStoreVo getThisMonth(StatsStoreDto statsStoreDto) {
        statsStoreDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
        statsStoreDto.setEndDateStr(DateTimeUtils.getCurrTime());
        statsStoreDto.setType(1);
        StatsStoreVo statsStoreVo = this.findFromStatsStore(statsStoreDto);
        //当天
        StatsStoreVo todayStatsStoreVo = this.findTodayStatsStoreFromOrder(statsStoreDto);
        this.twoStatsStoreVoAdd(statsStoreVo, todayStatsStoreVo);
        return statsStoreVo;
    }

    private void twoStatsStoreVoAdd(StatsStoreVo statsStoreVo, StatsStoreVo statsStoreVo1) {
        //消费会员个数
        statsStoreVo.setMemberConsumeNum(statsStoreVo.getMemberConsumeNum()+ statsStoreVo1.getMemberConsumeNum());
        //新增的会员
        statsStoreVo.setMemberNewNum(statsStoreVo.getMemberConsumeNewNum()+ statsStoreVo1.getMemberConsumeNewNum());
        //老会员
        statsStoreVo.setMemberConsumeOldNum(statsStoreVo.getMemberConsumeOldNum() + statsStoreVo1.getMemberConsumeOldNum());
        //留存手机号会员数量
        statsStoreVo.setLeaveMemberPhoneNumber(statsStoreVo.getLeaveMemberPhoneNumber()+statsStoreVo1.getLeaveMemberPhoneNumber());

        //最高客单价
        Integer max = statsStoreVo.getMaxTotalAmount().compareTo(statsStoreVo1.getMaxTotalAmount());
        statsStoreVo.setMaxTotalAmount(max<0?statsStoreVo1.getMaxTotalAmount():statsStoreVo.getMaxTotalAmount());
        //最低客单价
        Integer min = statsStoreVo.getMinTotalAmount().compareTo(statsStoreVo1.getMinTotalAmount());
        statsStoreVo.setMinTotalAmount(min<0?statsStoreVo1.getMinTotalAmount():statsStoreVo.getMinTotalAmount());
        //平均客价
        if(statsStoreVo.getTurnover().add(statsStoreVo1.getTurnover()).compareTo(BigDecimal.ZERO)>0){
            //总金额
            BigDecimal totalTurnover =  statsStoreVo.getTurnover().add(statsStoreVo1.getTurnover());
            //消费顾客
            Integer memberConsumeNum =  statsStoreVo.getMemberConsumeNum() + statsStoreVo1.getMemberConsumeNum();
            if(memberConsumeNum>0){
                //计算平均价格
                statsStoreVo.setAveragePrice(totalTurnover.divide(BigDecimal.valueOf(memberConsumeNum),2, BigDecimal.ROUND_HALF_UP));
            }else{
                statsStoreVo.setAveragePrice(BigDecimal.ZERO);
            }
        }else{
            statsStoreVo.setAveragePrice(BigDecimal.ZERO);
        }
    }

    private StatsStoreVo findFromStatsStore(StatsStoreDto statsStoreDto) {
        StatsStoreVo statsStoreVo = statsStoreDao.findStoreStatsCustomer(statsStoreDto);
        return statsStoreVo;
    }

    private StatsStoreVo findTodayStatsStoreFromOrder(StatsStoreDto statsStoreDto) {

        if(ObjectUtils.isNotEmpty(statsStoreDto.getHour())){
            //获取昨天的开始时间和结束时间 格式yyyy-MM-dd HH:mm:ss
            statsStoreDto.setStartTime(DateTimeUtils.parseLocalDate(DateTimeUtils.getYesterday()).format(DateTimeUtils.START_DATETIME_FORMATTER));
            statsStoreDto.setEndTime(DateTimeUtils.parseLocalDate(DateTimeUtils.getYesterday()).format(DateTimeUtils.END_DATETIME_FORMATTER));
        }else{
            //今天开始时间
            statsStoreDto.setStartTime(DateTimeUtils.getTodayStartTime());
            //今天结束时间
            statsStoreDto.setEndTime(DateTimeUtils.getTodayEndTime());
        }
        //查询当天消费顾客
        StatsStoreVo statsUserVo = statsStoreDao.findCustomerCount(statsStoreDto);


        //根据场地查询 当天新会员数量
        Integer newNum = memberStoreBalanceService.findMemberNewNumByStoreId(statsStoreDto);
        statsUserVo.setMemberConsumeNewNum(newNum);
        //根据场地查询 当天老会员数量
        Integer oldNum = memberStoreBalanceService.findMemberOldNumByStoreId(statsStoreDto);
        statsUserVo.setMemberConsumeOldNum(oldNum);

        //消费会员个数：现金笔数 + 抖音核销笔数 + 美团核销笔数。注意：现金笔数按memberId为空的来计算
        statsUserVo.setMemberConsumeNum(newNum + oldNum +
                                    statsUserVo.getCashCount()+
                                    statsUserVo.getMeiTuanCount()+
                                    statsUserVo.getDouYinCount());

        //活动
        StatsStoreVo activityStatsUser = statsUserDao.findActivityMoneyByStoreId(statsStoreDto);

        //最高客单价
        Integer max = statsUserVo.getMaxTotalAmount().compareTo(activityStatsUser.getMaxTotalAmount());
        statsUserVo.setMaximumUnitPrice(max<0?activityStatsUser.getMaxTotalAmount():statsUserVo.getMaxTotalAmount());
        //最低客单价
        Integer min = statsUserVo.getMinTotalAmount().compareTo(activityStatsUser.getMinTotalAmount());
        statsUserVo.setMiniimumUnitPrice(min<0?activityStatsUser.getMinTotalAmount():statsUserVo.getMinTotalAmount());
        //平均客价
        if(statsUserVo.getTurnover().compareTo(BigDecimal.ZERO) > 0 && statsUserVo.getMemberConsumeNum() > 0){
            statsUserVo.setAveragePrice(statsUserVo.getTurnover().divide(BigDecimal.valueOf(statsUserVo.getMemberConsumeNum()),2, BigDecimal.ROUND_HALF_UP));
        }else{
            statsUserVo.setAveragePrice(BigDecimal.ZERO);
        }
        //根据场地 留存手机号会员数量
        Integer countPhoneNumber = memberDao.findCountMemberByMchStoreId(statsStoreDto);
        statsUserVo.setLeaveMemberPhoneNumber(countPhoneNumber);

        return statsUserVo;
    }
}
